<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<title>
		Javascript Audio Processing
	</title>
	<script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js?autoload=true&amp;skin=sunburst&amp;lang=css" defer="defer"></script>
	<!-- show all line numbers-->
	<style type="text/css">
		body {
			font-family:Arial, Helvetica, sans-serif;
		}
		.prettyprint ol.linenums>li {
			list-style-type: decimal
		}
	</style>
	<script src="../build/maximilian.js"></script>
</head>

<body>
	<h1> Maximilian.js Examples </h1>
	<p></p>
	<ul>
		<li>MFCC Processing Demo (see console for output)</li>
	</ul>
	<button id="playButton">Play</button>
	<!-- <pre class="prettyprint lang-js linenums:true" id="quine" style="border:4px solid #88c" > -->
	</pre>
</body>

<!-- Our javascript code -->
<script type="text/javascript">

	let maxi = maximilian();

	var maxiEngine = new maxi.maxiAudio();

	let playAudio = () => {

		maxiEngine.init(0);

		var osc1=new maxi.maxiOsc();
		var osc2=new maxi.maxiOsc();
		var osc3=new maxi.maxiOsc();
		var fft = new maxi.maxiFFT();
		fft.setup(1024,512,1024);
		var ifft = new maxi.maxiIFFT();
		ifft.setup(1024,512,1024);
		var mags = new maxi.VectorFloat();
		var phases = new maxi.VectorFloat();
		mags.resize(512,0);
		phases.resize(512,0);

		var mfccAnalyser = new maxi.maxiMFCC();
		var mfccs = new maxi.VectorDouble();
		mfccs.resize(8,0);
		mfccAnalyser.setup(fft.getNumBins(), fft.getNumBins()/2, mfccs.size(), 20, 20000);

		maxiEngine.play = function(input) {
			var mix=0;
			mix = osc1.sawn(maxi.maxiMap.linexp(osc2.phasor(0.2), 0, 1, 100, 5000));
			if (fft.process(mix, maxi.maxiFFTModes.WITH_POLAR_CONVERSION)) {
	      mags = fft.getMagnitudes();
	      phases = fft.getPhases();
	      //shift bins up
	      for(let i=511; i > 0; i--) {
	        if (i > 10) {
	          mags.set(i, mags.get(i-10));
	        }else{
	          mags.set(i,0);
	        }
	      }
				mfccs = mfccAnalyser.mfcc(mags);
				let mfccStr = "";
				for(let i=0; i < mfccs.size(); i++) {
					mfccStr = mfccStr + mfccs.get(i) + ",";
				}
				console.log(mfccStr);
	    }
		 	mix = ifft.process(mags,phases, maxi.maxiIFFTModes.SPECTRUM);
		 	return mix;
		}
	}

	const playButton = document.getElementById('playButton');
	playButton.addEventListener("click", () => playAudio());

</script>

</html>
